package com.changdu.seatunnel.admin.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.changdu.seatunnel.admin.entity.DataInstance;
import com.changdu.seatunnel.admin.mapper.DataInstanceMapper;
import com.changdu.seatunnel.admin.pojo.TableField;
import com.changdu.seatunnel.admin.service.DataSourceService;
import com.changdu.seatunnel.admin.util.DatabaseUtil;

public class DatabaseDatasourceConfigServiceImpl implements DataSourceService {

    private final DataInstanceMapper dataInstanceMapper;

    public DatabaseDatasourceConfigServiceImpl(DataInstanceMapper dataInstanceMapper) {
    	this.dataInstanceMapper = dataInstanceMapper;
    }
    
    @Override
    public List<String> getInstances(String dataCenter) {
        LambdaQueryWrapper<DataInstance> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DataInstance::getDataCenter, dataCenter)
                .select(DataInstance::getInstance)
                .groupBy(DataInstance::getInstance);
        
        return dataInstanceMapper.selectList(wrapper)
                .stream()
                .map(DataInstance::getInstance)
                .toList();
    }

    @Override
    public List<String> getDatabases(String dataCenter, String instance) {
		DataInstance config = getDatasourceConfig(dataCenter, instance);
		if (Objects.isNull(config)) return new ArrayList<>();

		return DatabaseUtil.getDatabases(config);
    }

    @Override
    public List<String> getTables(String dataCenter, String instance, String database) {
        DataInstance config = getDatasourceConfig(dataCenter, instance);
        if (Objects.isNull(config)) return new ArrayList<>();

        return DatabaseUtil.getTables(config, database);
    }

    @Override
    public List<TableField> getTableStructure(String dataCenter, String instance, String database, String table) {
        DataInstance config = getDatasourceConfig(dataCenter, instance);
        if (Objects.isNull(config)) return new ArrayList<>();

        return DatabaseUtil.getTableStructure(config, database, table);
    }

    private DataInstance getDatasourceConfig(String dataCenter, String instance) {
        LambdaQueryWrapper<DataInstance> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DataInstance::getDataCenter, dataCenter)
                .eq(DataInstance::getInstance, instance)
                .last("LIMIT 1");
        return dataInstanceMapper.selectOne(wrapper);
    }

	@Override
	public DataInstance selectByDcCodeAndInstance(String dataCenter, String instance) {
		LambdaQueryWrapper<DataInstance> query = new LambdaQueryWrapper<DataInstance>()
				.eq(DataInstance::getDataCenter, dataCenter).eq(DataInstance::getInstance, instance);
		return dataInstanceMapper.selectOne(query);
	}

} 